package com.wkhyapp.lm.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.LoadMoreView;
import com.lidong.photopicker.PhotoPickerActivity;
import com.lidong.photopicker.SelectModel;
import com.lidong.photopicker.intent.PhotoPickerIntent;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.wkhyapp.lm.R;
import com.wkhyapp.lm.adapter.MemberAdapter;
import com.wkhyapp.lm.base.SuperFragment;
import com.wkhyapp.lm.constant.Constant;
import com.wkhyapp.lm.contract.IndexPagesPresenter;
import com.wkhyapp.lm.contract.IndexPagesView;
import com.wkhyapp.lm.http.vo.Banner;
import com.wkhyapp.lm.http.vo.Member;
import com.wkhyapp.lm.utils.IdUtils;
import com.wkhyapp.lm.utils.ImageLoadUtil;
import com.wkhyapp.lm.utils.MemberUtils;
import com.wkhyapp.lm.view.CheckInActivity;
import com.wkhyapp.lm.view.LoginActivity;
import com.wkhyapp.lm.view.SearchActivity;
import com.wkhyapp.lm.view.SearchResultActivity;
import com.wkhyapp.lm.view.ShopActivity;
import com.wkhyapp.lm.weigit.Marquee;
import com.wkhyapp.lm.weigit.MarqueeView;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


public class PagesFragment extends SuperFragment<IndexPagesPresenter> implements IndexPagesView{

    private static final int REQUEST_CAMERA_CODE = 10;
    private ArrayList<String> imagePaths = new ArrayList<>();
    private ArrayList<String> imgList = new ArrayList<>();
    @BindView(R.id.refresh_view)
    SwipeRefreshLayout refresh_view;
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;
    private MemberAdapter memberAdapter;
    private List<Member> members;
    private int mCurrentPage = 1;
    private Integer categoryId;
    private MZBannerView mzBanner;
    List<Banner> bannerList = null;
    private RelativeLayout dearch_rl;
    MarqueeView marqueeView;
    List<Marquee> marquees = new ArrayList<>();
    private View headView;
    private ImageView imageView3,imageView4;
    private ImageView sqrz_iv;
    public static PagesFragment newInstance(Integer createId,String name) {
        PagesFragment fragment = new PagesFragment();
        Bundle args = new Bundle();
        args.putInt("cid", createId);
        args.putString("name", name);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initUI() {
         headView = View.inflate(context, R.layout.index_head, null);
         sqrz_iv = (ImageView) headView.findViewById(R.id.sqrz_iv);
         marqueeView = (MarqueeView) headView.findViewById(R.id.marqueeView);
        dearch_rl= (RelativeLayout) headView.findViewById(R.id.dearch_rl);
        imageView3 = (ImageView) headView.findViewById(R.id.imageView3);
        imageView4 = (ImageView) headView.findViewById(R.id.imageView4);
        mzBanner = (MZBannerView) headView.findViewById(R.id.mzBanner);
        categoryId = getArguments().getInt("cid");
        bannerList = new ArrayList<>();
        members = new ArrayList<>();
        memberAdapter = new MemberAdapter(R.layout.item_member_index,members);
        memberAdapter.addHeaderView(headView);
        refresh_view.setColorSchemeColors(Color.parseColor("#FFEC48"),Color.parseColor("#FFEC48"));
        GridLayoutManager manager = new GridLayoutManager(getContext(),4);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 0) {
                    return 1;
                }

                if (position == recycler_view.getAdapter().getItemCount() - 1) {
                    return 4;
                }
                return 1;
            }
        });
        recycler_view.setLayoutManager(manager);
        recycler_view.setAdapter(memberAdapter);
        refresh_view.setRefreshing(false);


    }


    public void jumpBanner(Banner banner){
        goTo(ShopActivity.class,banner.getId());
    }

    @Override
    protected IndexPagesPresenter createPresenter() {
        return mPresenter = new IndexPagesPresenter(this);
    }

    @Override
    protected void initData() {
        mPresenter.getBanner();
        mPresenter.getNewlySettled();
        mPresenter.getMemberMore(categoryId,mCurrentPage,36);

    }

    @Override
    public void setBanner(List<Banner> banner) {
        bannerList.addAll(banner);
        List<String> images = new ArrayList<String>();
        for(int i =0;i<banner.size();i++){
            images.add(banner.get(i).getCoverImg());
        }
        mzBanner.setPages(images, new MZHolderCreator<BannerViewHolder>() {
            @Override
            public BannerViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });
        mzBanner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener(){
            @Override
            public void onPageClick(View view, int i) {
                jumpBanner(bannerList.get(i));
            }
        });

        if(banner!=null){
            if(banner.size()>=1){
                mzBanner.start();
            }
        }

        marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View textView) {
            goTo(ShopActivity.class,marquees.get(position).getId());
            }
        });
    }

    @Override
    public void setNewlySettled(List<Member> memberList) {
        for (Member m:memberList) {
            Marquee marquee = new Marquee();
            marquee.setId(m.getId());
            marquee.setImgUrl(m.getHeadImg());
            marquee.setTitle(m.getNickname());
            marquee.setTime(m.getCreateTime());
            marquees.add(marquee);

        }
        marqueeView.setImage(true);
        marqueeView.startWithList(marquees);

    }

    @Override
    protected void initListener() {

        memberAdapter.setLoadMoreView(new LoadMoreView() {
            @Override
            public int getLayoutId() {
                return R.layout.view_index_load_more;
            }

            @Override
            protected int getLoadingViewId() {
                return com.chad.library.R.id.load_more_loading_view;
            }
            @Override
            protected int getLoadFailViewId() {
                return com.chad.library.R.id.load_more_load_fail_view;
            }
            @Override
            protected int getLoadEndViewId() {
                return com.chad.library.R.id.load_more_load_end_view;
            }
        });

        dearch_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goTo(SearchActivity.class);
            }
        });

        memberAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mCurrentPage = mCurrentPage+1;
                mPresenter.getMemberMore(categoryId,mCurrentPage,36);

            }
        });
        refresh_view.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPage = 1;
                mPresenter.getMember(categoryId,mCurrentPage,36);
            }
        });

        mzBanner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int i) {
                jumpBanner(bannerList.get(i));
            }
        });

        imageView3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M && getActivity().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }else{
                    PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(false); // 是否显示拍照
                    intent.setMaxTotal(1); // 最多选择照片数量，默认为6
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                }
            }
        });

        imageView4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M && getActivity().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }else{
                    PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(false); // 是否显示拍照
                    intent.setMaxTotal(1); // 最多选择照片数量，默认为6
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                }
            }
        });

        memberAdapter.setCallBack(new MemberAdapter.callBack() {
            @Override
            public void action(Member member) {
                goTo(ShopActivity.class,member.getId());
            }
        });

        sqrz_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(MemberUtils.isLogin()){
                    goTo(CheckInActivity.class);
                }else{
                    TToast("请先登录");
                    goTo(LoginActivity.class);
                }
            }
        });
    }




    @Override
    public void setMemberList(List<Member> memberList) {
        members.clear();
        if(memberList!=null&&memberList.size()>0){
            members.addAll(memberList);
        }
        memberAdapter.notifyDataSetChanged();
        refresh_view.setRefreshing(false);
        memberAdapter.loadMoreComplete();


    }


    @Override
    public void setMemberMore(List<Member> memberMore) {
        if(memberMore.size()==0){
            memberAdapter.loadMoreComplete();
            memberAdapter.loadMoreEnd();
        }else{
            members.addAll(memberMore);
            memberAdapter.notifyDataSetChanged();
            memberAdapter.loadMoreComplete();
        }
    }




    @Override
    public int getLayoutId() {
        return R.layout.fragment_pages;
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    imgList.clear();
                    imgList.addAll(list);
                    if(list.size()>0){
                        mPresenter.getToken();
                    }
                    break;
            }
        }
    }

    Configuration config = new Configuration.Builder().build();
    UploadManager uploadManager = new UploadManager(config);
    @Override
    public void setToken(String token) {
        String key = "sousuo_"+MemberUtils.getMember()+"_"+System.currentTimeMillis()+"_"+ IdUtils.getShartUUID();
        uploadManager.put(imgList.get(0), key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        if(info.isOK()) {
                            goTo(SearchResultActivity.class, Constant.qiniuUrl+key);
                        } else {
                        }
                    }
                }, null);
    }



    public static class BannerViewHolder implements MZViewHolder<String> {
        private ImageView mImageView;
        @Override
        public View createView(Context context) {
            // 返回页面布局文件
            View view = LayoutInflater.from(context).inflate(R.layout.banner_index,null);
            mImageView = (ImageView) view.findViewById(R.id.banner_image);
            return view;
        }
        @Override
        public void onBind(Context context, int position, String data) {

            if(data.startsWith("http")){
                ImageLoadUtil.setRoundImage_Normal(context,data,6,mImageView);
            }else{

                ImageLoadUtil.setRoundImage_Normal(context,"https://a.wkhyapp.com"+data,6,mImageView);
            }

        }
    }
}
